package com.loukou.lkt.lkt.utils;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import com.loukou.lkt.lkt.bo.ExcelConstant;




public class FileUtil {
	private static final Logger logger = Logger.getLogger(FileUtil.class);
	private static final String UPLOAD_FILE_PATH = "tmp_file/upload/";
	private static final String DOWNLOAD_FILE_PATH = "tmp_file/download/";

	/**
	 * 将上传的文件保存到临时目录
	 * @param file
	 * @return null=保存失败, file=保存的文件
	 */
	public static File saveFile (MultipartFile file) {
		// 判断文件是否为空  
        if (file != null && !file.isEmpty()) {
            try {
            	// 文件保存路径  
                StringBuilder filePath = new StringBuilder();
                filePath.append(generateTempFilename(getUploadFilePath()))
                		.append(ExcelConstant.POINT)
                		.append(ExcelUtils.getPostfix(file.getOriginalFilename()));
                // 转存文件  
                File fileSaved = new File(filePath.toString());
                file.transferTo(fileSaved);
                return fileSaved;
            } catch (Exception e) {  
                logger.warn("FileUtils.saveFile FAILED.", e);
                return null;
            } 
        } 
        else {
            return null;        	
        }
	}
	/**
	 * 返回文件下载ResponseEntity
	 * @param file
	 * @return
	 */
	public static ResponseEntity<byte[]> getResponseEntity(File file) {
		 //读取文件并返回
        HttpHeaders headers = new HttpHeaders();  
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
        headers.setContentDispositionFormData("attachment", file.getPath());  
        try {
			return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),  
			                                  headers, HttpStatus.CREATED);
		} catch (IOException e) {
			logger.warn("FileUtils.getResponseEntity FAILED", e);
			return null;
		}
	}
	
	/**
	 * 获得上传文件的存放路径
	 * @return
	 */
	public static String getUploadFilePath() {
		return FileUtil.class.getClassLoader().getResource(UPLOAD_FILE_PATH).getPath();
	}
	/**
	 * 获得下载文件的存放路径
	 * @return
	 */
	public static String getDownloadFilePath() {
		return FileUtil.class.getClassLoader().getResource(DOWNLOAD_FILE_PATH).getPath();
	}
	
	/**
	 * 生成临时文件的文件名,不包括后缀
	 */
	public static String generateTempFilename(String path){
		StringBuilder filename = new StringBuilder();
		
		filename.append(path).append(System.currentTimeMillis());
		return filename.toString();
	}
}
